import instance from "./requery";


export const getUserInfo = () => {
    return instance.request({
        url: 'user',
        method: 'get'
        // token已在request拦截器中通过header传递
    })
}
// 编辑用户信息
export const updateUserInfo = (data) => {
    return instance.request({
        url: 'user',
        method: 'patch',
        data
    })
}
// 获取用户已发布房源列表
export const getUserHouses = () => {
    return instance.request({
        url: 'user/houses',
        method: 'get'
        // token已在request拦截器中通过header传递
    })
}

// 下架房屋（删除房源）
export const deleteHouse = (houseCode) => {
    // 直接返回axios请求，不额外包装
    return instance.request({
        url: 'user/houses',
        method: 'post',
        data: { houseCode } // 将houseCode作为请求体传递
        // token已在request拦截器中通过header传递
    });
}



//获取管理员管理用户管理 数据接口
export const getAdminUserData = () => {
    return instance({
        url:'/admin/users',
        method:'GET',
    })
}

//管理员开启或禁用接口
export const startOrdisabled = (id,disabled) => {
    return instance ({
        url:`/admin/users/${id}`,
        method:'PATCH',
        disabled
    })
}

//获取房屋
export const usersData = () => {
    return instance({
        url:'/admin/houses',
        method:'GET'
    })
}




// 用户
const TOKEN_KEY = 'token'
const ROLE_KEY = 'role'
const USERNAME_KEY = 'username'
const USER_ID_KEY = 'userId'

const ADMIN_ROLE_KEYWORDS = ['admin', 'manager', '管理员', 'manager']

function normalizeRole(input) {
  if (!input) return 'user'
  const normalized = String(input).trim().toLowerCase()
  return ADMIN_ROLE_KEYWORDS.some((keyword) => normalized.includes(keyword)) ? 'admin' : 'user'
}

export function resolveRole(payload = {}) {
  if (!payload || typeof payload !== 'object') return 'user'

  const candidate =
    payload.role ??
    payload.userRole ??
    payload.userType ??
    payload.identity ??
    payload.type ??
    (Array.isArray(payload.roles) ? payload.roles.find(Boolean) : undefined)

  if (candidate) {
    return normalizeRole(candidate)
  }

  if (payload.isAdmin || payload.admin === true) {
    return 'admin'
  }

  return 'user'
}

export function storeAuth({ token, role, username, userId }) {
  if (token) {
    localStorage.setItem(TOKEN_KEY, token)
  }
  if (role) {
    localStorage.setItem(ROLE_KEY, role)
  }
  if (username) {
    localStorage.setItem(USERNAME_KEY, username)
  }
  if (userId) {
    localStorage.setItem(USER_ID_KEY, userId)
  }
}

export function clearAuth() {
  localStorage.removeItem(TOKEN_KEY)
  localStorage.removeItem(ROLE_KEY)
  localStorage.removeItem(USERNAME_KEY)
  localStorage.removeItem(USER_ID_KEY)
  sessionStorage.clear()
}

export function getToken() {
  return localStorage.getItem(TOKEN_KEY)
}

export function getRole() {
  return localStorage.getItem(ROLE_KEY) ?? 'user'
}

export function isAdmin() {
  return getRole() === 'admin'
}

export function hasActiveSession() {
  return Boolean(getToken())
}